frappe.query_reports["manual_in_stock_table"] = {
    "filters": [
        {
            "fieldname": "customer_name",
            "label": "客户",
            "fieldtype": "Link", 
            "options": "Customer",
            "width": 80,
            "description": "选择客户"
        },
    ],

    onload: function(report) {
        // 增加自定义按钮
        report.page.add_inner_button(__('手动入库'), function() {
            const datatable = frappe.query_report.datatable;
            if (!datatable) return;

            // 获取勾选的行索引
            const checked_rows = datatable.rowmanager.getCheckedRows();
            if (!checked_rows.length) {
                frappe.show_alert({ message: __('请先勾选至少一行'), indicator: 'red' });
                return;
            }

            const rows = datatable.datamanager.rows;
            const columns = datatable.datamanager.columns;
            console.log(columns)
            const result = {};
            
            checked_rows.forEach(rowIndex => {
                const row = rows[rowIndex];
                
                // 根据列索引获取值的函数
                const getValue = (fieldname) => {
                    const col = columns.find(c => c.fieldname === fieldname);
                    if (!col) {
                        console.warn(`列 ${fieldname} 不存在`);
                        return '';
                    }
                    const colIndex = col.colIndex;
                    // 根据你的数据结构，直接访问 content 属性
                    return row[colIndex] ? row[colIndex].content : '';
                };
                // 获取所有字段的值（根据新的列结构）
                const salesOrder = getValue('parent');
                const idx = parseInt(getValue('idx')) || 0;
                const item_code = getValue('item_code'); // 虽然列隐藏了，但数据还在
                const customer_name = getValue('customer_name');
                const final_cus = getValue('final_cus');
                const specification = getValue('specification');
                const plating_type = getValue('plating_type');
                const batch_no = getValue('batch_no');
                const qty = parseFloat(getValue('qty')) || 0;
                const in_qty = parseFloat(getValue('in_qty')) || 0;
                const available_qty = parseFloat(getValue('available_qty')) || 0;
                const remaining_qty = parseFloat(getValue('remaining_qty')) || 0;

                if (!result[salesOrder]) result[salesOrder] = [];
                result[salesOrder].push({ 
                    idx: idx,
                    item_code: item_code,
                    customer_name: customer_name,
                    final_cus: final_cus,
                    specification: specification,
                    plating_type: plating_type,
                    batch_no: batch_no,
                    qty: qty,
                    in_qty: in_qty,
                    available_qty: available_qty,
                    remaining_qty: remaining_qty,
                    new_in_qty: undefined, // 默认入库数量
                    produce_line: '' // 默认产线
                });
            });

            console.log('处理后的数据:', result);
            
            // 检查是否有有效数据
            const validOrders = Object.keys(result);
            if (validOrders.length === 0) {
                frappe.show_alert({ 
                    message: __('没有找到有效的订单数据'), 
                    indicator: 'red' 
                });
                return;
            }
            
            // 打开手动入库对话框
            openManualStockDialog(result);
        });

        const originalRefresh = report.refresh;
        
        // 重写刷新函数
        report.refresh = function() {
            const datatable = frappe.query_report.datatable;
            const r = originalRefresh.apply(this, arguments);
            // console.log(frappe.query_report.datamanager)
            setTimeout(() => {
                if (datatable && datatable.rowmanager) {
                    datatable.rowmanager.checkMap = {};
                    datatable.rowmanager.checkedRows = [];
                }
                // colorizeReportColumns()
            }, 50);
            return r;
        };
    },
formatter: function(value, row, column, data, default_formatter) {
    let formatted_value = default_formatter(value, row, column, data);

    // 获取列索引（colIndex 从0开始）
    const colIndex = column.colIndex || 0;

    // 偶数列白色，奇数列灰色
    const bgColor = (colIndex % 2 === 1) ? "#ffffff" : "#e2e3e5";

    formatted_value = `<span style="
        display:block;
        width:100%;
        height:100%;
        box-sizing:border-box;
        background-color:${bgColor};
    ">${formatted_value}</span>`;

    return formatted_value;
},
    get_datatable_options(options) {
        return Object.assign(options, {
            treeView: false,
            checkedRowStatus: false,
            checkboxColumn: true
        });
    },
    

};
function colorizeReportColumns() {
    const datatable = frappe.query_report.datatable;
    if (!datatable) return;

    const rows = datatable.wrapper.querySelectorAll(".dt-row");
    if (!rows.length) return;

    rows.forEach(row => {
        const cells = row.querySelectorAll(".dt-cell");
        cells.forEach((cell, colIndex) => {
            // 跳过第一列复选框
            if (colIndex === 0) return;

            // 奇偶列背景色
            const color = colIndex % 2 === 1 ? "#e2e3e5" : "#ffffff";

            // 直接修改行内 style，覆盖 datatable 自带的 !important
            cell.style.backgroundColor = color;
            const content = cell.querySelector(".dt-cell__content");
            if (content) {
                content.style.backgroundColor = color;
            }
        });
    });
}


// 手动入库对话框函数
function openManualStockDialog(stockData) {
    const production_lines = [
        "201自动线镀锌",
        "201自动线镀锌镍",
        "201清洗",
        "202自动线",
        "202酸锌手动线",
        "202碱锌镍手动线",
        "202酸锌镍手动线",
        "外发线",
    ];

    // 创建对话框
    const dialog = new frappe.ui.Dialog({
        title: '手动入库',
        fields: [
            { fieldname: 'table_html', fieldtype: 'HTML' }
        ],
        primary_action_label: '提交入库',
        primary_action(values) {
            const items = [];
            let valid = true;
            
            // 只收集勾选的行数据
            for (const salesOrder in stockData) {
                stockData[salesOrder].forEach((item, index) => {
                    // 检查该行是否被勾选
                    const $row = dialog.$wrapper.find(`tr[data-sales-order="${salesOrder}"][data-item-index="${index}"]`);
                    const isChecked = $row.find('.so-stock-checkbox').is(':checked');
                    
                    if (!isChecked) {
                        return; // 跳过未勾选的行
                    }
                    
                    const newQty = parseFloat(item.new_in_qty) || 0;
                    const produce_line = item.produce_line || '';

                    if (!produce_line) {
                        frappe.msgprint(`销售订单 ${salesOrder} 行 ${item.idx} 的产线不能为空`);
                        valid = false;
                        return false;
                    }
                    if (newQty == undefined||newQty == 0) {
                        frappe.msgprint(`销售订单 ${salesOrder} 行 ${item.idx}，入库数量不能为空或为零`);
                        valid = false;
                        return false;
                    }
                    // if (newQty > item.remaining_qty) {
                    //     frappe.msgprint(`销售订单 ${salesOrder} 物料 ${item.item_code}，入库数量 ${newQty} 不能大于未入库数量 ${item.remaining_qty}`);
                    //     valid = false;
                    //     return false;
                    // }

                    items.push({ 
                        sales_order: salesOrder,
                        idx: item.idx, 
                        item_code: item.item_code, 
                        new_in_qty: newQty, 
                        produce_line: produce_line 
                    });
                });
            }

            if (!valid || items.length === 0) {
                if (items.length === 0) {
                    frappe.msgprint('请至少勾选一行数据进行入库操作');
                }
                return false;
            }

            // 确认框
            frappe.confirm(
                `确认要提交 ${items.length} 个物料的手动入库吗？`,
                () => {
                    // 按销售订单分组提交
                    const ordersData = {};
                    items.forEach(item => {
                        if (!ordersData[item.sales_order]) {
                            ordersData[item.sales_order] = [];
                        }
                        ordersData[item.sales_order].push({
                            idx: item.idx,
                            new_in_qty: item.new_in_qty,
                            produce_line: item.produce_line
                        });
                    });

                    // 提交所有销售订单
                    let processed = 0;
                    let totalOrders = Object.keys(ordersData).length;
                    let successCount = 0;
                    let failCount = 0;
                    
                    for (const salesOrder in ordersData) {
                        frappe.call({
                            method: 'matrix_fo.module.sales.sales_order.manual_in_stock',
                            args: { 
                                sales_order_no: salesOrder, 
                                items: ordersData[salesOrder] 
                            },
                            freeze: true,
                            freeze_message: `正在处理销售订单 ${salesOrder}... (${processed + 1}/${totalOrders})`,
                            callback(r) {
                                processed++;
                                if (!r.exc) {
                                    if (r.message.status === "success") {
                                        console.log(`销售订单 ${salesOrder} 入库成功:`, r.message);
                                        successCount++;
                                    } else {
                                        console.error(`销售订单 ${salesOrder} 入库失败:`, r.message);
                                        failCount++;
                                        frappe.msgprint(`❌ 销售订单 ${salesOrder} 入库失败: ${r.message.message}`);
                                    }
                                } else {
                                    console.error(`销售订单 ${salesOrder} 处理异常:`, r.exc);
                                    failCount++;
                                    frappe.msgprint(`❌ 销售订单 ${salesOrder} 处理异常`);
                                }
                                
                                // 所有订单处理完成
                                if (processed === totalOrders) {
                                    let message = `已完成 ${processed} 个销售订单的手动入库处理`;
                                    let indicator = 'green';
                                    
                                    if (failCount > 0) {
                                        message += ` (成功: ${successCount}, 失败: ${failCount})`;
                                        if (successCount === 0) {
                                            indicator = 'red';
                                        } else {
                                            indicator = 'orange';
                                        }
                                    }
                                    
                                    frappe.msgprint({
                                        message: message,
                                        title: '入库完成',
                                        indicator: indicator
                                    });
                                    dialog.hide();
                                    // 刷新报表
                                    if (frappe.query_report) {
                                        frappe.query_report.refresh();
                                    }
                                }
                            }
                        });
                    }
                },
                () => { 
                    frappe.show_alert({ message: __('已取消入库操作'), indicator: 'yellow' });
                }
            );
        }
    });

    // 构建表格HTML
    // 构建表格HTML - 更新列结构
    let tableRows = '';
    let totalItems = 0;

    for (const salesOrder in stockData) {
        const orderItems = stockData[salesOrder];
        cus_name=orderItems[0].customer_name
        totalItems += orderItems.length;
        
        // 添加销售订单标题行
        tableRows += `
            <tr style="background-color: #f8f9fa; font-weight: bold;">
                <td colspan="12" style="padding: 8px; border: 1px solid #dee2e6;">
                    📋 销售订单: ${salesOrder} (共 ${orderItems.length} 个物料),客户名称 ${cus_name}
                </td>
            </tr>
        `;
        
        // 添加该销售订单的物料行
        orderItems.forEach((item, index) => {
            tableRows += `
                <tr class="selectable-row" data-sales-order="${salesOrder}" data-item-index="${index}" data-idx="${item.idx} style="cursor: pointer;">
                    <td style="text-align:center;">
                        <input type="checkbox" class="so-stock-checkbox" 
                            data-sales-order="${salesOrder}"
                            data-item-index="${index}"
                            "
                            >
                    </td>
                    <td>${item.final_cus || ''}</td>
                    <td>${item.specification || ''}</td>
                    <td>${item.plating_type || ''}</td>
                    <td>${item.qty.toFixed(3)}</td>
                    <td>${item.in_qty.toFixed(3)}</td>
                    <td>${item.available_qty.toFixed(3)}</td>
                    <td class="remaining-qty">${item.remaining_qty.toFixed(3)}</td>
                    <td>
                    <div style="display: flex; align-items: center; gap: 5px;">
                    <input type="number" class="new-in-input form-control" 
                    value="${item.new_in_qty}" 
                    style="width:80px"
                    max="${item.remaining_qty}"
                    step="0.001"
                                data-sales-order="${salesOrder}"
                                data-item-index="${index}">
                                <button type="button" class="btn btn-xs btn-default max-quantity-btn" 
                                title="设置为最大可入库数量" style="white-space: nowrap;"
                                data-sales-order="${salesOrder}"
                                data-item-index="${index}">
                                最大
                                </button>
                                </div>
                                </td>
                                <td>
                                <select class="produce-line-input form-control" style="width:150px" required
                                data-sales-order="${salesOrder}"
                                data-item-index="${index}">
                                <option value="" ${!item.produce_line ? 'selected' : ''}>请选择产线</option> 
                                ${production_lines.map(l => 
                                `<option value="${l}" ${item.produce_line === l ? 'selected' : ''}>${l}</option>`
                            ).join('')}
                            </select>
                            </td>
                    <td>${item.batch_no || ''}</td>
                </tr>
            `;
        });
    }

    const tableHTML = `
        <style>
            .selected-row {
                background-color: #e6f2ff !important;
            }
            .max-quantity-btn {
                padding: 2px 8px;
                font-size: 12px;
            }
            .selectable-row:hover {
                background-color: #f5f5f5;
            }
            .sales-order-header {
                background-color: #e9ecef;
                font-weight: bold;
            }
            .click-produce-line-section {
                background-color: #f8f9fa;
                padding: 10px;
                margin-bottom: 10px;
                border-radius: 4px;
                border: 1px solid #dee2e6;
            }
        </style>
        
        <div style="margin-bottom:10px;">
            <strong>共 ${Object.keys(stockData).length} 个销售订单, ${totalItems} 个物料行</strong>
        </div>
        
        <!-- 批量操作区域 -->
        <div class="click-produce-line-section">
            <div style="display: flex; align-items: center; gap: 10px;">
                <span style="font-weight: bold;">批量操作:</span>
                <! -- 全选 -->
                <button type="button" class="btn btn-default" id="btn-so-stock-select-all">
                    全选
                </button>
                <!-- 批量设置产线选择框 -->
                <select id="default_produce_line" class="form-control" style="width:200px;">
                    <option value="">批量设置产线</option>
                    ${production_lines.map(l => `<option value="${l}">${l}</option>`).join('')}
                </select>
                <!-- 全部最大入库按钮 -->
                <button type="button" class="btn btn-default" id="set-all-max-quantity">
                    更新所有库存
                </button>
            </div>
        </div>

        <!-- 筛选和逐行操作区域 -->
        <div style="margin-bottom:10px;">
            <!-- 新增销售订单筛选框 -->
            <input type="text" id="filter_sales_order" placeholder="销售订单" class="form-control" style="width:200px; display:inline-block; margin-right:10px;">
            <input type="text" id="filter_spec" placeholder="规格" class="form-control" style="width:200px; display:inline-block; margin-right:10px;">
            <input type="text" id="filter_batch_no" placeholder="批号" class="form-control" style="width:200px; display:inline-block; margin-right:10px;">
            <!-- 点击行自动设置产线选择框 -->
            <select id="click_produce_line" class="form-control" 
                style="width:200px; display:inline-block; margin-left:10px;">
                <option value="">点击行设置产线</option>
                ${production_lines.map(l => `<option value="${l}">${l}</option>`).join('')}
            </select>
        </div>
        
        <div style="max-height: 600px; overflow-y: auto;">
            <table class="table table-bordered" style="margin-top:10px;">
                <thead>
                    <tr>
                        <th style="width:30px;text-align:center;"><input type="checkbox" id="so-stock-select-all"></th>
                        <th>终客户</th>
                        <th>规格</th>
                        <th>镀种</th>
                        <th>订单数量</th>
                        <th>当前入库数量</th>
                        <th>当前可出库数量</th>
                        <th>未入库数量</th>
                        <th>本次入库数量</th>
                        <th>产线</th>
                        <th>批次</th>
                    </tr>
                </thead>
                <tbody>${tableRows}</tbody>
            </table>
        </div>
    `;
    
    dialog.fields_dict.table_html.$wrapper.html(tableHTML);

    // 实时更新stockData中的数据
    function updateStockData(salesOrder, itemIndex, field, value) {
        if (stockData[salesOrder] && stockData[salesOrder][itemIndex]) {
            stockData[salesOrder][itemIndex][field] = value;
        }
    }

    // 绑定事件
    dialog.$wrapper.on('input change', '.new-in-input', function() {
        const salesOrder = $(this).data('sales-order');
        const itemIndex = $(this).data('item-index');
        const value = parseFloat($(this).val()) || 0;
        updateStockData(salesOrder, itemIndex, 'new_in_qty', value);
    });

    dialog.$wrapper.on('change', '.produce-line-input', function() {
        const salesOrder = $(this).data('sales-order');
        const itemIndex = $(this).data('item-index');
        const value = $(this).val();
        updateStockData(salesOrder, itemIndex, 'produce_line', value);
    });

    // 筛选功能
    dialog.$wrapper.find('#filter_sales_order, #filter_batch_no, #filter_spec').on('input', function() {
        const salesOrder = dialog.$wrapper.find('#filter_sales_order').val().trim();
        // const code = dialog.$wrapper.find('#filter_item_code').val().trim();
        const batch = dialog.$wrapper.find('#filter_batch_no').val().trim();
        const spec = dialog.$wrapper.find('#filter_spec').val().trim();

        dialog.$wrapper.find('tbody tr.selectable-row').each(function() {
            const $row = $(this);
            const row_sales_order = $row.data('sales-order') || ''; // 销售订单
            // const row_code = $row.find('td').eq(2).text().trim(); // 物料号
            // const row_batch = $row.find('td').eq(6).text().trim(); // 收货批
            const row_batch_no = $row.find('td').eq(10).text().trim(); // 批号
            const row_spec = $row.find('td').eq(2).text().trim(); // 规格

            const salesOrderMatch = !salesOrder || row_sales_order.includes(salesOrder);
            // const codeMatch = !code || row_code.includes(code);
            // const batchMatch = !batch || row_batch.includes(batch);
            const batchNoMatch = !batch || row_batch_no.includes(batch);
            const specMatch = !spec || row_spec.includes(spec);

            if (salesOrderMatch && batchNoMatch && specMatch) {
                $row.show();
            } else {
                $row.hide();
            }
        });
    });

    // 最大按钮点击事件
    dialog.$wrapper.on('click', '.max-quantity-btn', function(e) {
        e.stopPropagation();
        const salesOrder = $(this).data('sales-order');
        const itemIndex = $(this).data('item-index');
        const $row = $(this).closest('tr');
        let remainingQty = parseFloat($row.find('.remaining-qty').text()) || 0;
        const $input = $row.find('.new-in-input');
        remainingQty = Math.round(remainingQty * 1000) / 1000;
        $input.val(remainingQty.toFixed(3));
        updateStockData(salesOrder, itemIndex, 'new_in_qty', remainingQty);
    });

    // 默认产线选择（批量设置）
    dialog.$wrapper.on('change', '#default_produce_line', function() {
        const default_line = $(this).val();
        if (default_line) {
            dialog.$wrapper.find('.produce-line-input').each(function() {
                const salesOrder = $(this).data('sales-order');
                const itemIndex = $(this).data('item-index');
                $(this).val(default_line);
                updateStockData(salesOrder, itemIndex, 'produce_line', default_line);
            });
            frappe.show_alert({ message: `已批量设置所有行为产线: ${default_line}`, indicator: 'green' });
        }
    });

    // 行点击事件 - 选中/取消选中，并自动设置产线
    dialog.$wrapper.on('click', '.selectable-row', function(e) {
        // 如果点击的是复选框、输入框、按钮或选择框，不触发行点击事件
        if ($(e.target).is('input, button, select, .max-quantity-btn, .so-stock-checkbox')) {
            return;
        }
        
        const $row = $(this);
        const $checkbox = $row.find('.so-stock-checkbox');
        const isChecked = $checkbox.is(':checked');
        
        // 切换选中状态
        $checkbox.prop('checked', !isChecked).trigger('change');
        
        // 获取点击行自动设置的产线
        const clickProduceLine = dialog.$wrapper.find('#click_produce_line').val();
        if (clickProduceLine) {
            const salesOrder = $row.data('sales-order');
            const itemIndex = $row.data('item-index');
            const $produceLineInput = $row.find('.produce-line-input');
            
            // 设置产线
            $produceLineInput.val(clickProduceLine).trigger('change');
            updateStockData(salesOrder, itemIndex, 'produce_line', clickProduceLine);
        }
    });

    // 选中行高亮
    dialog.$wrapper.on('change', '.so-stock-checkbox', function() {
        const $row = $(this).closest('tr');
        if ($(this).is(':checked')) {
            $row.addClass('selected-row');
        } else {
            $row.removeClass('selected-row');
        }
    });
    
    // 全部最大入库按钮点击事件
    dialog.$wrapper.on('click', '#set-all-max-quantity', function() {
        let updatedCount = 0;
        
        // 遍历所有可见的行
        dialog.$wrapper.find('tbody tr.selectable-row:visible').each(function() {
            const $row = $(this);
            const salesOrder = $row.data('sales-order');
            const itemIndex = $row.data('item-index');
            const remainingQty = parseFloat($row.find('.remaining-qty').text()) || 0;
            const $input = $row.find('.new-in-input');
            const maxQty = Math.round(remainingQty * 1000) / 1000;
            
            // 设置入库数量为最大可入库数量
            $input.val(maxQty.toFixed(3));
            updateStockData(salesOrder, itemIndex, 'new_in_qty', maxQty);
            updatedCount++;
        
        });
        
        frappe.show_alert({ 
            message: `已为 ${updatedCount} 个物料更新库存`, 
            indicator: 'green' 
        });
    });

    // 全选/取消全选
    dialog.$wrapper.on('change', '#so-stock-select-all', function() {
        const checked = $(this).is(':checked');
        dialog.$wrapper.find('.so-stock-checkbox').prop('checked', checked).trigger('change');
    });

    // 全选按钮点击事件
    dialog.$wrapper.on('click', '#btn-so-stock-select-all', function() {
        const $selectAllCheckbox = dialog.$wrapper.find('#so-stock-select-all');
        const isCurrentlyChecked = $selectAllCheckbox.is(':checked');
        
        // 切换全选状态
        $selectAllCheckbox.prop('checked', !isCurrentlyChecked).trigger('change');
    });

    dialog.show();
    dialog.$wrapper.find('.modal-dialog').css('max-width', '90%');
}